AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')

AccessorFunc(ENT, "Texture", "FlashlightTexture")
ENT:SetFlashlightTexture("effects/flashlight001")

function ENT:Initialize()
	self.BaseClass.Initialize(self)
	self.Entity:SetColor(200,0,0,255)
	lastuse = CurTime()
	self.dt.On = false
end

function ENT:Think()
    if(self.Entity:IsPowered() == false) then 
		SafeRemoveEntity(self.flashlight)
		self.flashlight = nil
		self:SetOn(false)
		self.Entity:SetColor(200,0,0,255)
		return
	end
	if (ValidEntity(self.dt.Owner)==false) then
		self.Entity:Remove()
	end
	self.Entity:NextThink(CurTime()+0.1)
end

function ENT:Use()
	if(CurTime() < lastuse+1) then return end
	if(self.Entity:IsPowered() == true) then 
		self.Entity:Toggle()
	end
		lastuse = CurTime()
end

//copy pasta from gmod ent.
function ENT:SetLightColor()
	local r = 0
	local b = 0
	local g = 0
	self:SetVar("lightr", r)
	self:SetVar("lightg", g)
	self:SetVar("lightb", b)
	
	self:SetColor(r, g, b, 255)
	
	self.m_strLightColor = Format("%i %i %i", r, g, b)
	
	if (self.flashlight) then
		self.flashlight:SetKeyValue("lightcolor", self.m_strLightColor)
	end

end

/*---------------------------------------------------------
   Name: Sets the texture
---------------------------------------------------------*/
function ENT:SetFlashlightTexture(tex)

	self.Texture = tex
	
	if (self.flashlight) then
		self.flashlight:Input("SpotlightTexture", NULL, NULL, self:GetFlashlightTexture())
	end
	
end

/*---------------------------------------------------------
   Name: Toggle
---------------------------------------------------------*/
function ENT:Toggle()

	if (self.flashlight) then
	
		SafeRemoveEntity(self.flashlight)
		self.flashlight = nil
		self:SetOn(false)
		self.Entity:SetColor(200,0,0,255)
		return
	
	end
	self.Entity:SetColor(255,255,255,255)
	self:SetOn(true)
	local angForward = self:GetAngles() + Angle(90, 0, 0)
	
	self.flashlight = ents.Create("env_projectedtexture")
	
		self.flashlight:SetParent(self.Entity)
		
		// The local positions are the offsets from parent..
		self.flashlight:SetLocalPos(Vector(0, 0, 0))
		self.flashlight:SetLocalAngles(Angle(90,90,90))
		
		// Looks like only one flashlight can have shadows enabled!
		self.flashlight:SetKeyValue("enableshadows", 1)
		self.flashlight:SetKeyValue("farz", 2048)
		self.flashlight:SetKeyValue("nearz", 8)
		
		//Todo: Make this tweakable?
		self.flashlight:SetKeyValue("lightfov", 50)
		
		// Color.. Bright pink if none defined to alert us to error
		self.flashlight:SetKeyValue("lightcolor", self.m_strLightColor or "100 100 100" )
		
		
	self.flashlight:Spawn()
	
	self.flashlight:Input("SpotlightTexture", NULL, NULL, self:GetFlashlightTexture())

end

function ENT:OnRemove()

end